// components/comment.js
Component({
  /**
   * 组件的生命周期，在这里面请求评论数据
   */
  lifetimes: {
    ready: function () {
      console.log("ready")
      this.triggerEvent('commentReady')
      console.log("comment data id=", this.data.resourceId)
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    resourceId: {
      type: String,
      value: ''
    } //学习资料id
  },

  /**
   * 组件的初始数据
   */
  data: {
    resourceId: "0", //学习资料id
    commentItems: [], //组件的父评论数组
    commentCount: 0, //评论总数
    inputVal: "",
    isDataOK: false, //控制组件加载的显示
    isLoadingMore: false, //加载更多的函数会用到
    min_height: 130,
    showReply: false, /*是否显示遮罩及评论*/
    reply: {fid: '', val: ''},/*在评论中输入的值*/
    maskHeight: 0 /*遮罩层的高度*/
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _getComments: function(id){
      console.log('c id=',id)
      this.data.resourceId = id
      //获取评论总条数
      let that = this
      const db = wx.cloud.database()
      const collection = db.collection('comments')
      if(this.data.resourceId == ''){ return }
      db.collection('comments').where({
        "resourceId": this.data.resourceId,
        "parentId": ""
      }).count().then(res => {
        console.log('total res = ', res)
        let total = res.total
        this.setData({commentCount: total})
        if(total != 0){//评论数不为0
          //请求前5条数据
          wx.cloud.callFunction({
            name: 'getComments',
            data:{
              id: this.data.resourceId
            }
          }).then(res => {
            console.log('前5', res)
            this.setData({commentItems: this.data.commentItems.concat(res.result), isDataOK: true})
          }).catch(err => {
            console.log(err)
          })
        }
      }).catch(err => {
        this.setData({isDataOK: true})
        console.log(err)
        return 0
      })
    },
    _showLeftComments: function () {
      this.setData({
          isLoadingMore: true
        },
        wx.cloud.callFunction({
          name: 'getComments',
          data:{
            id: this.data.resourceId,
            skip: this.data.commentItems.length,
            limitnum: 20
          }
        }).then(res => {
          console.log('剩余', res)
          this.setData({commentItems: this.data.commentItems.concat(res.result), isLoadingMore: false})
        }).catch(err => {
          console.log(err)
        })
      )
    },
    _inputTyping: function (e) {
      this.setData({
        inputVal: e.detail.value
      });
    },
    _sendComment: function (e) {//需要确定用户要发送的是父评论还是子评论
      console.log('_sendComment data = ', this.data)
      console.log('_sendComment e = ', e)
      const c_type = e.currentTarget.dataset.type //评论类型 
      console.log('发送留言')
      //显示上传中提示
      wx.showLoading({title: '上传中', mask: true})
      //处理，点击上传后最好再禁用输入框
      const database = wx.cloud.database()
      if(c_type === 'f'){ //发送父评论，数据从inputVal中取
        //1.保存到数据库
        database.collection('comments').add({
          data: {
            resourceId: this.data.resourceId,
            content: this.data.inputVal,
            date: database.serverDate(),
            parentId: '',
            username: '临时用户'
          }
        }).then(res => {
          console.log('上传子评论成功，返回值为:',res)
          wx.hideLoading()
          wx.showToast({title: '成功'})
          setTimeout(function(){wx.hideToast()}, 1500)
          //2.保存到数据库成功后再，保存到页面，否则提示出错
          this.data.commentItems.push({
            "pc": {
              "content": this.data.inputVal,
              "date": Date(),
              "username": "临时用户",
              "resourceId": this.data.resourceId
            },
            "sc": []
          })
          //3.更新页面信息
          this.setData({
            commentItems: this.data.commentItems,
            commentCount: this.data.commentCount + 1,
            nowCount: this.data.nowCount + 1
          })
        }).catch(err => {
          wx.hideLoading()
          wx.showToast({title: '失败', icon: 'error'})
          setTimeout(function(){wx.hideToast()}, 1500)
        })
      }else if(c_type === 'c'){ //发送子评论，数据从reply中取
        //1.保存到数据库
        let username = 'Unknown'
        let fid = this.data.reply.fid
        database.collection('comments').add({
          data: {
            resourceId: this.data.resourceId,
            content: this.data.reply.val,
            date: database.serverDate(),
            parentId: fid,
            username: username
          }
        }).then(res => {
          console.log('添加评论 res=', res)
          wx.hideLoading()
          wx.showToast({title: '成功'})
          setTimeout(function(){wx.hideToast()}, 1500)
          //2.保存到数据库成功后再，保存到页面，否则提示出错
          this.selectComponent("#" + fid)._addOneSubComment(res._id, username, this.data.reply.val)
          this._hideReply()
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
          wx.showToast({title: '失败', icon: 'error'})
          setTimeout(function(){wx.hideToast()}, 1500)
          this._hideReply()
        })
      }else{
        console.log("Warning, not 'f' or 'c'")
      }
    },
    _setMinHeight: function (n) {
      this.setData({
        min_height: n
      })
    },
    /*以下是回复评论相关*/
    _showReply: function(e){
      //subcomment和commentitem组件触发抛出reply事件时，均会触发这个函数
      console.log("comment组件，显示评论：_showReply, e=",e)
      const fid = e.detail.fid
      this.data.reply.fid = fid
      //1.获取页面高度，计算并确定遮罩区的高度
      let windowH = wx.getSystemInfoSync().windowHeight //屏幕高度
      this.setData({maskHeight: windowH - 190, showReply: true}, function(){console.log('设置window完成')})
      console.log('_showReply data = ', this.data)
    },
    _hideReply: function(){//隐藏遮罩及评论区
      this.setData({showReply: false})
    },
    _inputSubComment: function(e){//textarea，用户输入的评论
      const text = e.detail.value
      console.log(text)
      this.data.reply.val = text //保存输入
    }
  }
})